package cn.wolfcde.luowowo.website.web.resolver;

import cn.wolfcde.luowowo.website.annotation.RedisParameter;
import cn.wolfcde.luowowo.website.key.CookieKey;
import cn.wolfcde.luowowo.website.util.CookieUtil;
import cn.wolfcode.luowowo.cache.service.IUserInfoRedisService;
import cn.wolfcode.luowowo.member.domain.UserInfo;
import com.alibaba.dubbo.config.annotation.Reference;
import net.bytebuddy.build.Plugin;
import org.springframework.core.MethodParameter;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.support.WebDataBinderFactory;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.method.support.ModelAndViewContainer;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Component
public class UserInfoResolver implements HandlerMethodArgumentResolver {

    @Reference
    private IUserInfoRedisService userInfoRedisService;

    @Override
    public boolean supportsParameter(MethodParameter methodParameter) {

        if(methodParameter.getParameterType() == UserInfo.class && methodParameter.hasParameterAnnotation(RedisParameter.class)){
            return true;
        }
        return false;
    }

    @Override
    public Object resolveArgument(MethodParameter methodParameter, ModelAndViewContainer modelAndViewContainer, NativeWebRequest nativeWebRequest, WebDataBinderFactory webDataBinderFactory) throws Exception {

        HttpServletRequest request = nativeWebRequest.getNativeRequest(HttpServletRequest.class);

        HttpServletResponse response = nativeWebRequest.getNativeResponse(HttpServletResponse.class);

        String token = CookieUtil.getToken(request, response);

        UserInfo userInfo = userInfoRedisService.getLoginUserInfoByToken(token);

        return userInfo;
    }
}